<template>
  <div class="route-field-configuration">
    <TopNavigation :showOrganizationSection="false" />
    <div class="page-header">
      <h2>路由字段配置</h2>
    </div>
    
    <div class="card">
      <div class="toolbar">
        <div class="search-container">
          <div class="input-group">
            <input
              type="text"
              class="input"
              placeholder="搜索应用名称或字段说明"
              v-model="searchKeyword"
              @keyup.enter="searchFields"
            />
            <button class="button--submit" @click="searchFields">
              搜索
            </button>
          </div>
        </div>
        <button class="btn btn-primary" @click="showAddModal">添加路由字段</button>
      </div>
      
      <!-- 路由字段卡片展示 -->
      <div class="fields-container">
        <div v-if="paginatedFields.length === 0" class="empty-state">
          <div class="empty-icon">🌐</div>
          <div class="empty-text">暂无路由字段数据</div>
          <div class="empty-hint">点击上方按钮添加路由字段</div>
        </div>
        
        <div v-else class="fields-grid">
          <div v-for="field in paginatedFields" :key="field.id" class="field-card">
            <div class="field-header">
              <div class="field-title-section">
                <h3 class="field-chinese-name">{{ field.chineseName }}</h3>
                <span class="field-english-name">{{ field.englishName }}</span>
              </div>
              <div class="action-buttons">
                <button class="edit-btn" @click="showEditModal(field)" title="编辑">
                  ✏️
                </button>
                <button class="delete-btn" @click="deleteField(field.id)" title="删除">
                  🗑️
                </button>
              </div>
            </div>
            
            <div class="field-content">
              <div class="field-description-section">
                <div class="section-title">字段说明</div>
                <div class="field-description">{{ field.description || '暂无说明' }}</div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 分页控件 -->
        <div class="pagination-container" v-if="paginatedFields.length > 0 || totalItems > 0">
          <div class="pagination">
            <button
              class="btn btn-default"
              @click="onPageChange(Math.max(1, page - 1))"
              :disabled="page === 1"
            >
              上一页
            </button>
            <span class="page-info">
              第 {{ page }} 页 / 共 {{ totalPages }} 页
            </span>
            <button
              class="btn btn-default"
              @click="onPageChange(Math.min(totalPages, page + 1))"
              :disabled="page >= totalPages || totalItems === 0"
            >
              下一页
            </button>
            <div class="page-size-selector">
              <span>每页显示:</span>
              <select class="select" v-model="pageSize" @change="onPageSizeChange">
                <option :value="5">5条</option>
                <option :value="10">10条</option>
                <option :value="20">20条</option>
                <option :value="50">50条</option>
              </select>
            </div>
          </div>
        </div>

        <!-- 空状态提示 -->
        <div v-if="paginatedFields.length === 0" class="empty-state">
          暂无路由字段数据
        </div>
      </div>
    </div>
    
    <!-- 新增/编辑路由字段模态框 -->
    <div v-if="showModal" class="modal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3 class="modal-title">{{ isEditMode ? '编辑路由字段' : '添加路由字段' }}</h3>
          <button class="btn btn-default" @click="closeModal">×</button>
        </div>
        <div class="modal-body">
          <div class="form-item">
            <label class="form-label">应用中文名</label>
            <input
              type="text"
              class="input"
              v-model="formData.chineseName"
              placeholder="请输入应用中文名"
              required
            />
          </div>
          <div class="form-item">
            <label class="form-label">应用英文名</label>
            <input
              type="text"
              class="input"
              v-model="formData.englishName"
              placeholder="请输入应用英文名"
              required
            />
          </div>
          <div class="form-item">
            <label class="form-label">字段说明</label>
            <textarea
              class="textarea"
              v-model="formData.description"
              placeholder="请输入字段说明"
              rows="3"
            ></textarea>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-default" @click="closeModal">取消</button>
          <button class="btn btn-primary" @click="saveField">
            {{ isEditMode ? '更新' : '确定' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import TopNavigation from '../components/TopNavigation.vue'
import { ref, computed, onMounted } from 'vue'
import * as routeFieldService from '../services/routeFieldService'

// 分页相关变量
const page = ref(1)
const pageSize = ref(10)

// 处理分页大小变化
const onPageSizeChange = () => {
  // 重置到第一页
  page.value = 1;
  // 立即重新计算totalPages，确保UI及时更新
  if (totalItems.value > 0) {
    totalPages.value = Math.ceil(totalItems.value / pageSize.value);
  }
  // 重新获取数据，这会重新计算totalPages
  fetchRouteFields();
}

// 处理页码变化
const onPageChange = (newPage) => {
  if (newPage >= 1 && newPage <= totalPages.value) {
    page.value = newPage;
    fetchRouteFields();
  }
}

// 初始化路由字段数据
const routeFields = ref([])

// 从后端获取路由字段数据
const fetchRouteFields = async () => {
  try {
    // 构建分页参数
    const params = {
      page: page.value - 1, // 后端通常从0开始计数
      size: pageSize.value
    };
    
    // 添加搜索参数
    if (searchKeyword.value.trim()) {
      params.search = searchKeyword.value.trim();
    }
    
    const response = await routeFieldService.getRoutingFields(params)
    const fieldData = response.data?.content || response.data || [];
    totalItems.value = response.data?.totalElements || response.data?.total || fieldData.length;
    // 计算总页数
    totalPages.value = Math.ceil(totalItems.value / pageSize.value);
    routeFields.value = fieldData;
  } catch (error) {
    showMessage('获取路由字段数据失败: ' + (error.message || '未知错误'), 'error')
    console.error('Failed to fetch route fields:', error)
  }
}

// 搜索关键词
const searchKeyword = ref('')

// 模态框相关状态
const showModal = ref(false)
const isEditMode = ref(false)
const currentFieldId = ref(null)
const formData = ref({
  chineseName: '',
  englishName: '',
  description: ''
})

// 过滤后的路由字段列表（后端分页，直接返回routeFields）
const filteredFields = computed(() => {
  return routeFields.value
})

// 分页相关变量
const totalItems = ref(0)
const totalPages = ref(0)
const paginatedFields = computed(() => {
  return routeFields.value
})

// 搜索路由字段
const searchFields = () => {
  page.value = 1;
  fetchRouteFields();
}

// 显示新增模态框
const showAddModal = () => {
  isEditMode.value = false
  currentFieldId.value = null
  formData.value = {
    chineseName: '',
    englishName: '',
    description: ''
  }
  showModal.value = true
}

// 显示编辑模态框
const showEditModal = (field) => {
  isEditMode.value = true
  currentFieldId.value = field.id
  formData.value = {
    chineseName: field.chineseName,
    englishName: field.englishName,
    description: field.description
  }
  showModal.value = true
}

// 关闭模态框
const closeModal = () => {
  showModal.value = false
}

// 保存路由字段
const saveField = async () => {
  // 验证必填字段
  if (!formData.value.chineseName.trim() || !formData.value.englishName.trim()) {
    showMessage('应用中文名和英文名不能为空', 'error')
    return
  }
  
  // 检查应用英文名是否已存在（编辑时排除当前字段）
  const isAppEnNameExists = routeFields.value.some(field => 
    field.englishName === formData.value.englishName && field.id !== currentFieldId.value
  )
  
  if (isAppEnNameExists) {
    showMessage('应用英文名已存在', 'error')
    return
  }
  
  try {
    if (isEditMode.value) {
      // 更新路由字段
      await routeFieldService.updateRoutingField(currentFieldId.value, formData.value)
      showMessage('路由字段更新成功', 'success')
    } else {
      // 新增路由字段
      await routeFieldService.createRoutingField(formData.value)
      showMessage('路由字段创建成功', 'success')
    }
    
    // 重新获取路由字段数据
    await fetchRouteFields()
    closeModal()
  } catch (error) {
    showMessage(`操作失败: ${error.message || '未知错误'}`, 'error')
    console.error('Failed to save route field:', error)
  }
}

// 删除路由字段
const deleteField = async (id) => {
  // 检查是否有路由配置正在使用该字段
  // 这里可以添加实际的检查逻辑
  const hasUsage = false // 模拟没有被使用
  
  if (hasUsage) {
    showMessage('该路由字段正在被使用，无法删除', 'error')
    return
  }
  
  if (confirm('确定要删除该路由字段吗？')) {
    try {
      await routeFieldService.deleteRoutingField(id)
      showMessage('路由字段删除成功', 'success')
      // 重新获取路由字段数据
      await fetchRouteFields()
    } catch (error) {
      showMessage(`删除失败: ${error.message || '未知错误'}`, 'error')
      console.error('Failed to delete route field:', error)
    }
  }
}

// 消息提示函数
const showMessage = (message, type = 'info') => {
  // 创建消息元素
  const msgElement = document.createElement('div')
  msgElement.className = `message message-${type}`
  msgElement.textContent = message
  
  // 添加到body
  document.body.appendChild(msgElement)
  
  // 3秒后移除
  setTimeout(() => {
    msgElement.style.opacity = '0'
    setTimeout(() => {
      document.body.removeChild(msgElement)
    }, 300)
  }, 3000)
}

// 组件挂载时的初始化
onMounted(() => {
  fetchRouteFields()
})
</script>

<style scoped>
.route-field-configuration {
  width: 100%;
}

.page-header {
  margin-bottom: var(--spacing-xl);
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
}

.page-header h2 {
  font-size: var(--font-size-xl);
  font-weight: 600;
  color: var(--text-primary);
  margin: 0;
}

/* 继承全局样式 */
.card {
  background-color: var(--bg-white);
  border-radius: var(--border-radius-md);
  box-shadow: var(--shadow-base);
  overflow: hidden;
  transition: box-shadow 0.3s ease;
}

.card:hover {
  box-shadow: var(--shadow-md);
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--spacing-lg);
  border-bottom: 1px solid var(--border-base);
  flex-wrap: wrap;
  gap: var(--spacing-lg);
}

.search-container {
  display: flex;
  gap: var(--spacing-sm);
  align-items: center;
  flex: 1;
  min-width: 280px;
}

/* 字段容器样式 */
.fields-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

/* 字段网格布局 */
.fields-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

/* 字段卡片样式 */
.field-card {
  background: #fff;
  border: 1px solid #e0e0e0;
  border-radius: 12px;
  padding: 20px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.field-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
  border-color: #007bff;
}

/* 字段头部 */
.field-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.field-title-section {
  flex: 1;
}

.field-chinese-name {
  margin: 0 0 6px 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
  line-height: 1.4;
}

.field-english-name {
  font-size: 13px;
  color: #666;
  background: #f8f9fa;
  padding: 4px 8px;
  border-radius: 4px;
  font-style: italic;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  gap: 8px;
}

.edit-btn,
.delete-btn {
  background: none;
  border: none;
  cursor: pointer;
  padding: 8px;
  border-radius: 6px;
  transition: background-color 0.2s ease;
  font-size: 16px;
}

.edit-btn:hover {
  background-color: #e3f2fd;
}

.delete-btn:hover {
  background-color: #ffebee;
}

/* 字段内容 */
.field-content {
  margin-top: 16px;
}

.field-description-section {
  margin-bottom: 16px;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  border: 2px solid #e5e7eb;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
}

.field-description-section:hover {
  border-color: #667eea;
  box-shadow: 0 4px 16px rgba(102, 126, 234, 0.15);
  transform: translateY(-2px);
  background: linear-gradient(135deg, #f0f4ff 0%, #ffffff 100%);
}

.section-title {
  font-size: 12px;
  color: #495057;
  margin-bottom: 12px;
  font-weight: 700;
  text-transform: uppercase;
  letter-spacing: 0.8px;
  padding: 6px 0;
  border-bottom: 2px solid #e9ecef;
  position: relative;
  transition: all 0.3s ease;
}

.section-title::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 0;
  width: 30px;
  height: 2px;
  background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
  border-radius: 1px;
}

.field-description {
  color: #374151;
  font-size: 14px;
  line-height: 1.6;
  margin: 0;
  word-wrap: break-word;
  overflow-wrap: break-word;
  font-weight: 500;
}

.field-description {
  font-size: 14px;
  color: #333;
  line-height: 1.5;
  background: #f8f9fa;
  padding: 8px;
  border-radius: 4px;
  border-left: 3px solid #007bff;
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 80px 20px;
  color: #999;
  background: #f8f9fa;
  border-radius: 12px;
  margin: 20px 0;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 16px;
  opacity: 0.6;
  display: block;
}

.empty-text {
  font-size: 16px;
  color: #666;
  margin-bottom: 8px;
  font-weight: 500;
}

.empty-hint {
  font-size: 14px;
  color: #999;
  margin-top: 8px;
}

.form-item {
  margin-bottom: var(--spacing-lg);
  transition: all 0.3s ease;
}

.form-item:focus-within {
  transform: translateX(5px);
}

.form-label {
  display: block;
  margin-bottom: var(--spacing-sm);
  font-weight: 500;
  color: var(--text-regular);
}

/* 文本域样式增强 */
.textarea {
  width: 100%;
  padding: var(--spacing-sm) var(--spacing-md);
  border: 1px solid var(--border-base);
  border-radius: var(--border-radius-md);
  font-size: var(--font-size-base);
  font-family: inherit;
  resize: vertical;
  transition: all 0.3s ease;
  min-height: 80px;
}

.textarea:focus {
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
  outline: none;
}

/* 按钮样式增强 */
.btn {
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: var(--spacing-xs);
}

.btn:hover {
  transform: translateY(-1px);
}

.btn:active {
  transform: translateY(0);
}

/* 模态框动画增强 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  backdrop-filter: blur(2px);
}

.modal-content {
  background-color: var(--bg-white);
  border-radius: var(--border-radius-md);
  box-shadow: var(--shadow-lg);
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  animation: modalFadeIn 0.3s ease;
}

@keyframes modalFadeIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.modal-header {
  padding: var(--spacing-lg);
  border-bottom: 1px solid var(--border-base);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-title {
  font-size: var(--font-size-lg);
  font-weight: 500;
  color: var(--text-primary);
  margin: 0;
}

.modal-body {
  padding: var(--spacing-lg);
  overflow-y: auto;
  flex: 1;
}

.modal-footer {
  padding: var(--spacing-lg);
  border-top: 1px solid var(--border-base);
  display: flex;
  justify-content: flex-end;
  gap: var(--spacing-md);
  flex-wrap: wrap;
}

/* 消息提示样式增强 */
.message {
  position: fixed;
  top: 80px;
  right: var(--spacing-xl);
  padding: var(--spacing-md) var(--spacing-lg);
  border-radius: var(--border-radius-md);
  color: #ffffff;
  font-size: var(--font-size-base);
  font-weight: 500;
  box-shadow: var(--shadow-lg);
  z-index: 1000;
  display: inline-flex;
  align-items: center;
  gap: var(--spacing-sm);
  animation: slideIn 0.3s ease;
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

.message-success {
  background-color: var(--success-color);
}

.message-error {
  background-color: var(--error-color);
}

/* 响应式调整 */
@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-container {
    width: 100%;
  }
  
  .table th,
  .table td {
    padding: 8px var(--spacing-md);
    font-size: var(--font-size-sm);
  }
  
  .modal-content {
    width: 95%;
    margin: 20px;
  }
  
  .message {
    right: var(--spacing-md);
    left: var(--spacing-md);
  }
}
</style>